<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formateEmployees" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="{row}">
              <!-- {{ formatDate(row.timeOfEntry,'---') }} -->
              {{ row.timeOfEntry | formatDate('---') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="pageSize"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <AddEmployee :show-dialog.sync="showDialog" @add-employee="getEmployeeList" />
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    <!-- <AddEmployee :show-dialog="showDialog" @update:showDialog="showDialog = false" /> -->
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters' // 在全局中注册了这个过滤器
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      userId: '',
      showRoleDialog: false,
      showDialog: false,
      page: 1,
      pageSize: 10,
      total: 0,
      list: [],
      loading: false
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 编辑角色
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    // 导出
    async handleDownload() {
      // this.downloadLoading = true
      // 获取所有数据
      const { data: { data: { rows }}} = await reqGetEmployeeList(1, this.total)
      // console.log(rows)
      // 表头
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const dataArr = this.formatJson(rows, headersArr, headersRelations)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr,
          data: dataArr,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    formatJson(rows, headersArr, headersRelations) {
      const result = []
      console.log(rows)
      // 1. 简单拼装二维数组
      rows.forEach(row => {
        const arr = []
        headersArr.forEach(header => {
          const englishKey = headersRelations[header]
          // correctionTime timeOfEntry
          let value = row[englishKey]
          if (['correctionTime', 'timeOfEntry'].includes(englishKey)) {
            // 处理转正日期和入职日期的格式
            value = formatDate(value, '/')
          }
          if (englishKey === 'formOfEmployment') {
            // 处理聘用形式
            value = EmployeeEnum.hireType.find(item => item.id === +value)?.value || '未知'
          }
          arr.push(value)
        })
        result.push(arr)
      })
      return result
    },
    addEmployee() {
      this.showDialog = true
    },
    delEmployee(id) {
      this.$confirm('确定删除改员工的信息吗？', '温馨提示', {
        type: 'warning'
      }).then(async() => {
        await reqDelEmployee(id)
        // 当页码大于1 并且 这一页只有一天数据，被点击删除后 页码往前一页
        if (this.page > 1 && this.list.length === 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployeeList()
      }).catch(() => {
      })
    },
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    async getEmployeeList() {
      this.loading = true
      const { data: { data }} = await reqGetEmployeeList(this.page, this.pageSize)
      // console.log(data)
      this.total = data.total
      this.list = data.rows
      this.loading = false
    },
    formateEmployees(row, column, cellValue, index) {
      // row - 当前行的数据
      // column - 包含当前列的属性
      // cellValue - 当前表格的数据
      // index - 下标
      // console.log({ row, column, cellValue, index })

      // 写法一
      // const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      // return obj ? obj.value : '未知'

      // 写法二
      return EmployeeEnum.hireType.find(item => item.id === +cellValue)?.value || '未知'
    }
  }
}
</script>

<style>

</style>

